<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
            margin: 0;
        }
        .wrapper{
            position: relative;
            margin: 0 auto;
            width: 90vw;
            border: 1px solid #aaa;
            margin-bottom: 2px;
        }
        .wrapper img{
            position: absolute;
            width: 220px;
            transition: all 0.5s;
        }
    </style>
</head>
<body>
    
    <div class="wrapper"></div>


    <script>

        // 获取外层容器
        var wrap = document.getElementsByClassName('wrapper')[0],
            imgWidth = 220;

        // 创建图片
        (function createImg() {
            for(var i = 0; i < 40; i ++) {
                var img = document.createElement('img');
                img.src = './assets/' + i + '.jpg';
                wrap.appendChild(img);
            }
            window.onload = setPosition;
        }())
        
        // 获取列数和间隙尺寸
        function size() {
            var column = Math.floor(wrap.offsetWidth / imgWidth),
                gapSum = column + 1,
                gap = (wrap.offsetWidth - imgWidth * column) / gapSum;
            return {
                column,
                gap
            }
        }

        function setPosition() {
            var info = size(),
                imgHeight = new Array(info.column);
            imgHeight.fill(0);
            var imgs = wrap.childNodes;
            for(var i = 0; i < imgs.length; i ++) {
                var min = Math.min.apply(null, imgHeight);
                imgs[i].style.top = min + 'px';
                var index = imgHeight.indexOf(min);
                imgHeight[index] += imgs[i].height + info.gap;
                var left = (index + 1) * info.gap + index * imgWidth;
                imgs[i].style.left = left + 'px';
            }
            const maxHeight = Math.max(...imgHeight);
            wrap.style.height = maxHeight + "px";
        }

        window.onresize = function () {
            var timer;
            if(timer) {
                clearInterval(timer);
            }
            timer = setTimeout(function () {
                setPosition();
            }, 500)
        }

    </script>

</body>
</html>